import { BaseEnvMirror } from "@/modules/dev-env/mirror/mirror.ts";
import { getMirrorOptions, type MirrorNames } from "@/modules/dev-env/mirror/data.ts";
import type { MirrorWebsiteFile } from "@common/spider-types.ts";
import type { ToolInstallVersionItem } from "@/modules/dev-env/common/types.ts";
import path from "@/framework/util/path.ts";
import semver from "semver";

export class ZkMirror extends BaseEnvMirror {
  constructor(name: MirrorNames) {
    super(getMirrorOptions(name, name === "apache" ? "/zookeeper/" : "/apache/zookeeper/"));
  }

  protected getDownloadList0(files: MirrorWebsiteFile[]): ToolInstallVersionItem[] | Promise<ToolInstallVersionItem[]> {
    const versionList: ToolInstallVersionItem[] = [];
    for (const it of files) {
      // 过滤非正式版本
      if (it.name.includes("beta") || it.name.includes("alpha") || it.name.includes("rc")) continue;

      if (it.type === "dir" && it.name.startsWith("zookeeper-")) {
        const version = it.name.replace("zookeeper-", "");

        // 华为云3.5.5及以下版本过滤掉,有些版本没有bin包
        if (this.id === "huaweicloud" && semver.compare(version, "3.5.5") === -1) {
          continue;
        }

        // https://mirrors.aliyun.com/apache/zookeeper/zookeeper-3.9.3/apache-zookeeper-3.9.3-bin.tar.gz
        const downloadUrl = `${this.url}${it.name}/apache-${it.name}-bin.tar.gz`;
        versionList.push({
          id: `zk-${it.name}`,
          name: path.basename(downloadUrl),
          version: version,
          url: downloadUrl,
          date: it.date,
          size: it.size,
        });
      }
    }

    versionList.sort((a, b) => semver.compare(b.version, a.version));
    return versionList;
  }
}
